<template>
    <base-modal
      class="material-apply-dialog-container"
      :default-style="true"
      :show.sync="visible"
      :title="$t('task.detail.partReturn')"
      width="900px"
      @closed="reset"
      append-to-body
    >

        <el-table 
            v-loading="listLoading" 
            header-row-class-name="base-table-header-v3" 
            row-class-name="base-table-row-v3" 
            :data="tableAllData" 
            max-height="500"
        >
            <template slot="empty">
                <BaseListForNoData v-show="!listLoading" table-type="smallTable" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
            </template>
            <el-table-column 
                v-for="(column, index) in columns" 
                :key="`${column.fieldName}_${index}`" 
                :label="column.displayName" 
                :prop="column.fieldName" 
                :width="column.width" 
                :fixed="column.isFixed"
            >
                <template slot-scope="scope">
                    <!-- start 返还数量 -->
                    <template v-if="column.fieldName === 'serialNumber'">
                        <div v-if="scope.row.serialNumber">{{ $formatFormField(column, scope.row) }}</div>
                        <template v-else>
                            <biz-remote-select
                                :placeholder="$t('common.placeholder.select')"
                                :value="scope.row.id"
                                :remote-method="fetchSparepart"
                                @input="updateSparepart"
                                >
                                <div class="search-in-part-item"  slot="option" slot-scope="{ option }">
                                    <template v-if="option.name && !partlLoading">
                                        <p>{{$t('common.base.name')}}：<span>{{ option.name }}</span></p>
                                        <p>{{$t('common.base.serialNumber')}}：<span>{{ option.serialNumber }}</span></p>
                                        <p>{{$t('common.base.type')}}：<span>{{ option.type }}</span></p>
                                        <p>{{$t('common.form.preview.sparepart.label3')}}：<span>{{ option.standard }}</span></p>
                                        <p v-if="option.description">{{$t('common.form.preview.sparepart.label5')}}<span>{{option.description}}</span></p>
                                    </template>
                                    <p class="no_empty" v-else>{{ partlLoading ? $t('common.base.loading') : $t('common.base.tip.noData') }}</p>
                                </div>
                                </biz-remote-select>
                        </template>
                    </template>
                    <!-- end 返还数量 -->
                    
                    <!-- start 返还数量 -->
                    <template v-else-if="column.fieldName === 'number'">
                        <el-input-number v-model="scope.row.number" step-strictly controls-position="right" :min="1" :max="setMaxNumber(scope.row.id)">
                        </el-input-number>
                    </template>
                    <!-- end 返还数量 -->

                    <!-- start 返还仓库 -->
                    <template v-else-if="column.fieldName === 'repertoryId'">
                        <!-- 返还个人 -->
                        <div v-if="isShowPersonal">
                            <template v-if="isOpenData">
                                <open-data ref="openDataRef" type="userName" :openid="loginUserInfo.staffId"></open-data>
                            </template>
                            <template v-else>{{ loginUserInfo.displayName }}</template>
                        </div>
                        <!-- 返还仓库 -->
                        <el-select v-else class='sale-price-select' v-model="scope.row.repertoryId" @change="e => changeWarehouse(e, scope.$index)">
                            <el-option
                                v-for="item in warehouseList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                                >
                            </el-option>
                        </el-select>
                    </template>
                    <!-- end 返还仓库 -->

                    <!-- start 操作 -->
                    <template v-else-if="column.fieldName === 'action'">
                        <el-button class="text-danger" type="text" size="mini" @click="deleteItem(scope)">{{$t('common.base.delete')}}</el-button>
                    </template>
                    <!-- end 操作 -->
                    <template v-else>{{ $formatFormField(column, scope.row) }}</template>
                </template>
            </el-table-column>
        </el-table>

        <div class="btn-group">
            <el-button type="primary" icon="el-icon-plus" plain size="mini" @click="addItem">{{$t('common.base.add2')}}</el-button>
        </div>

        <div class="dialog-footer" slot="footer">
            <el-button :disabled="pending" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
            <el-button type="primary" :disabled="pending" @click="submit">{{$t('common.base.submit')}}</el-button>
        </div>
    </base-modal>
</template>

<script>
import { findComponentUpward } from '@src/util/assist';
import _ from 'lodash';
import { isOpenData } from '@src/util/platform';
import { getRootWindow } from '@src/util/dom';
import * as TaskApi from '@src/api/TaskApi';
const MAX_NUMBER = 99999999;

export default {
  name: 'parts-return-dialog',
  props: {
    field: {
      type: Object,
      default: () => ({}),
    },
    cardSparepartList: {
      type: Array,
      default: () => [],
    },
    warehouseList: {
      type: Array,
      default: () => [],
    },
    columns: {
        type: Array,
        default: () => []
    }
  },
  data() {
    return {
        pending: false,
        visible: false,
        listLoading: false,
        tableAllData: [],
        keyword: '',
        returnType: '',
        isOpenData,
        emptyData: {},
        partlLoading: false,
        maxNumber: MAX_NUMBER,
    };
  },
  computed: {
    setting() {
      return this.field?.setting || {};
    },
    // 向上查找组件
    taskReceiptEditComponent() {
      return findComponentUpward(this, 'task-receipt-edit-view') || {};
    },
    // 已选备件列表
    taskReceiptSparePartList() {
      const parts = _.cloneDeep(this.taskReceiptEditComponent?.form?.sparepart || [])
        return parts.map(x => {
            delete x.primaryId
            return {
                ...x,
                id: x.sparePartId
            }
        });
    },
    // 已选备件返还列表
    taskReceiptSparePartReturnList() {
        return this.taskReceiptEditComponent?.form?.sparePartsReturnExpense || [];
    },
    isShowPersonal() {
        return this.returnType === 'personal';
    },
    // 当前用户数据
    loginUserInfo() {
        const RootWindow = getRootWindow(window);
        const { userId, displayName, staffId } = RootWindow?.loginUser || {};
        return {
            userId,
            displayName,
            staffId
        }
    },
    // 备件清单已出库的ids
    cardSparepartIds() {
      return this.cardSparepartList?.map(item => item.relatedId)
    }
  },
  methods: {
    // 设置返还的最大数量
    setMaxNumber(id) {
      // 仅备件清单中的物料可再限制数量只能是备件出库的数量
      if(this.setting?.onlySpartListReturn) {
        return this.cardSparepartList?.find(item => item.relatedId === id)?.useNum ?? this.maxNumber
      }else {
        return this.maxNumber
      }
    },
        open(type) {
            this.returnType = type;
            const newPartList = [];
            const selectedIds = this.taskReceiptSparePartReturnList.map(x => x.primaryId);
            // 已核销备件的旧件必须返还
            if(this.setting?.usedSparePartMustReturn){
                const sparePartList = this.taskReceiptSparePartList.filter(x => !selectedIds.includes(x.id));
                newPartList.unshift(...sparePartList);
            }
            // 已申领未核销的备件必须返还
            if(this.setting?.applySparePartMustReturn){
                // 备件清单的已出库数 - 备件的用量数

                let arr = [];
                let obj = {};

                let cardPartList = this.cardSparepartList.map(x => {
                    return {
                        ...x,
                        number: x.useNum,
                        id: x.relatedId
                    }
                })
                cardPartList = cardPartList.filter(x => !selectedIds.includes(x.id));
                
                if(this.taskReceiptSparePartList.length) {
                    cardPartList.forEach(cardItem => {
                        this.taskReceiptSparePartList.forEach(taskItem => {
                            if(taskItem.serialNumber === cardItem.serialNumber && cardItem.useNum - taskItem.number > 0) {
                                arr.push(cardItem)
                            }
                            if(taskItem.serialNumber !== cardItem.serialNumber && !obj[cardItem.serialNumber]) {
                                arr.push(cardItem)
                            }
                        })
                    })
                    newPartList.unshift(...arr);
                }else {
                    newPartList.unshift(...cardPartList);
                }
            }

            // 仅备件清单中的物料可返还(默认带入备件清单已出库的备件)
            if(this.setting?.onlySpartListReturn) {
              let arr = [];
              let cardPartList = this.cardSparepartList.map(x => {
                return {
                  ...x,
                  number: x.useNum,
                  id: x.relatedId
                }
              })
              cardPartList = cardPartList.filter(x => !selectedIds.includes(x.id))
              cardPartList?.forEach(item => {
                if(newPartList?.every(zitem => zitem.id !== item.id)) {
                  arr.push(item)
                }
              })
              newPartList.unshift(...arr)
            }
            newPartList.forEach(x => {
                x.number = x.number ?? 1;
                x.primaryType = x.type;
                x.type = '备件返还';
                if(x.repertoryId && !x.repertoryId.includes('/')) {
                    x.repertoryId = '';
                    x.repertoryName = '';
                }
                if(this.isShowPersonal && !x.repertoryId) {
                    x.repertoryId = this.loginUserInfo.userId
                    x.repertoryName = this.loginUserInfo.displayName;
                }
            })
            this.tableAllData = _.uniqBy(_.cloneDeep(newPartList), 'serialNumber');
            this.visible = true;
            this.addItem();
        },
        submit() {
            let showTips = [];
            const data = this.tableAllData.filter(x => x.serialNumber).map(x => {
                if(!x.repertoryId) showTips.push(`【${x.name}】`);
                return {
                    ...x,
                    isPerson: Boolean(this.isShowPersonal)
                }
            });
            if(showTips.length) return this.$platform.alert(this.$t('task.setting.spareReturnLabel2', {arr: showTips.join('、')}));
            
            this.$emit('submit', data);
            this.visible = false;
        },
        reset() {
            this.emptyData = {};
            this.tableAllData = [];
        },
        // 添加行
        addItem() {
            if(this.tableAllData.some(x => !x.serialNumber)) return;
            this.tableAllData.push(this.emptyData);
        },
        // 删除行
        deleteItem({row, $index}) {
            this.tableAllData.splice($index, 1);
        },
    // 获取备件
    async fetchSparepart(params) {
      this.partlLoading = true;
      const { keyword, pageNum, pageSize } = params
      try {
        let model = {
          keyWord: keyword,
          pageNum,
          pageSize,
          enable: 1,
          cardId: ''
        }
        // 仅备件清单中的物料可返还
        if(this.setting?.onlySpartListReturn) {
          model.ids = this.cardSparepartIds
        }
       let res = await TaskApi.getSparePartByUserTagList(model);
        this.partlLoading = false;
        if (!res.success) return;
        res.result.list = res.result.list.map(item => {
          return {
            label: item.name,
            value: item.id,
            ...item,
          }
        });

        return res.result;
      } catch (error) {
        this.partlLoading = false;
        console.warn('fetchSparepart -> error', error);
      } 
    },
    // 搜索备件
    async searchSparepart(params = {}) {
      return this.fetchSparepartList(params);
    },
    // 更新备件数据
    updateSparepart(value) {
        let newValue = value[0];
        this.tableAllData.pop();

        let newItem = {
            ...newValue,
            primaryType: newValue.type,
            type: '备件返还',
            number: 1,
        }
        if(this.isShowPersonal) {
            newItem.repertoryId = this.loginUserInfo.userId,
            newItem.repertoryName = this.loginUserInfo.displayName
        }
        this.tableAllData.push(newItem)
    },
    changeWarehouse(val, index) {
        const arr = val.split('/');
        this.tableAllData[index].repertoryId = val;
        this.tableAllData[index].repertoryName = arr[1];
    }
    }
};
</script>

<style lang="scss" scoped>
::v-deep .list-wrapper {
    width: 200px !important;
}
.btn-group {
    padding-top: 10px;
    button {
        border-radius: 4px;
    }
}
</style>
